const http = require('http')
const fs = require('fs')
const url = require('url')
const mimes = require('./lib/mime')
const { join, extname, resolve } = require('path')
const qs = require('querystring')

const rootpath = join(__dirname, 'www')

let num = 0
http.createServer((req, res) => {
    let errpath=join(rootpath,"./404.html")
    let { pathname, query } = url.parse(req.url, true)
    pathname = pathname === '/' ? './index.html' : pathname
    let filepath = join(rootpath, pathname)
    // console.log(filepath)
    //  if (fs.existsSync(filepath)) {

    if (req.method === "POST") {
        let a = {};
        // const ext = extname(filepath).slice(1)
        // const mime = mimes[ext]
        res.setHeader('content-type', 'text/html;charset=utf-8')
            if (pathname == '/login2') {

                let postData = ""
                req.on('data', chunk => postData += chunk)
                req.on('end', () => {
                    // console.log(qs.parse(postData));
                    let user = fs.readFileSync(resolve('./data/user.txt'), 'utf-8')
                    let arr = user.split(",")
                    for (var i = 0; i < arr.length; i++) {
                        let b = arr[i].split("=")
                        a[b[0]] = b[1]
                    }
                    if (num < 3) {
                        if (a.username !== qs.parse(postData).username || a.pwd !== qs.parse(postData).pwd) {
                            num++
                            res.end(JSON.stringify({code:1,msg:'账号或密码不正确','num':num}))
                        }
                        else if (a.username == qs.parse(postData).username && a.pwd == qs.parse(postData).pwd) {
                            res.end(JSON.stringify({code:0,msg:'登陆成功','num':num}))
                        }
                    } else {
                        res.end(JSON.stringify({code:2,msg:'今日次数用尽，不可登录','num':num}))
                    }
                    console.log(num)


                })
            }
        // }
        // else{
        //     res.statusCode = 404
        //     res.end(fs.readFileSync(errpath))
        // }
        }
        else {
            if (req.url !== './favicon.ico') {
                pathname = pathname === '/' ? './index.html' : pathname
                let filepath = join(rootpath, pathname)
                if (fs.existsSync(filepath)) {
                    const ext = extname(filepath).slice(1)
                    const mime = mimes[ext]
                    res.setHeader('content-type', mime)
                    let html
    
                    if ('html' === ext) {
                        // console.log(query)
    
                        html = fs.readFileSync(filepath, 'utf-8')
                        html = html.replace(/\{\{\s*(\w+)\s*\}\}/g, function (preg, match) {
                            return query[match]
                        })
                    } else {
                        html = fs.readFileSync(filepath)
                    }
                    res.end(html)
                } else {
                    res.statusCode = 404
                    res.end(fs.readFileSync(errpath))
                }
            }
        }   
    // } else{
    //         res.statusCode = 404
    //         res.end(fs.readFileSync(errpath))
    //     } 

}).listen(3000, '0.0.0.0')